<template>
  <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
    class="demo-ruleForm" :size="formSize" status-icon>
    <el-form-item label="功能商类型" prop="vendorType">
      <el-radio-group v-model="ruleForm.vendorType">
        <el-radio value="个人">个人</el-radio>
        <el-radio value="企业">企业</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="负责人手机号" prop="responsiblePhone">
      <el-input v-model="ruleForm.responsiblePhone" />
    </el-form-item>

    <el-form-item label="负责人姓名" prop="responsibleName">
      <el-input v-model="ruleForm.responsibleName" />
    </el-form-item>

    <el-form-item label="供应商名称" prop="vendorName">
      <el-input v-model="ruleForm.vendorName" />
    </el-form-item>

    <el-form-item label="身份证" prop="identityCard">
      <el-input v-model="ruleForm.identityCard" />
    </el-form-item>

    <el-form-item label="所在地" prop="arearAdd">
      <el-cascader v-model="value" :options="options" :props="prop" @change="handleChange" clearable />
      <el-input v-model="ruleForm.arearAdd" id="searchInputId" class="common-layout" size="small" placeholder="输入关键词搜索位置"
        style="height:25px;width:26%;margin-left:1%;" />
      <el-button @click="searchLocation">搜索</el-button>

    </el-form-item>
    <div class="gdmap-container">
      <div id="container" style="width: 100%; height: 300px;"></div>
    </div>

    <el-form-item label="所属行业" prop="industryName">
      <el-input v-model="ruleForm.industryName" />
    </el-form-item>

    <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
      <el-input v-model="ruleForm.unifiedSocialCreditCode" />
    </el-form-item>

    <el-form-item label="助记码" prop="mnemonics">
      <el-input v-model="ruleForm.mnemonics" />
    </el-form-item>

    <el-form-item label="供应商属性" prop="vendorAttributes">
      <el-input v-model="ruleForm.vendorAttributes" />
    </el-form-item>


    <el-form-item label="所属单位" prop="businessId">
      <el-select v-model="ruleForm.businessId" placeholder="所属单位">
        <el-option label="总部" :value="1" />
        <el-option label="分公司" :value="2" />
      </el-select>
    </el-form-item>

    <el-form-item label="使用状态" prop="useState">
      <el-radio-group v-model="ruleForm.useState">
        <el-radio :value="true">启用</el-radio>
        <el-radio :value="false">禁用</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="引用单位" prop="unitsOfReference">
      <el-input v-model="ruleForm.unitsOfReference" />
    </el-form-item>

    <el-form-item label="备注" prop="vendorDesc">
      <el-input v-model="ruleForm.vendorDesc" type="textarea" />
    </el-form-item>

    <h2>服务人员</h2>

    <el-form-item label="所属市场" prop="markets">
      <el-select v-model="ruleForm.markets" placeholder="所属市场">
        <el-option label="玉林市犀浦镇牛羊市场" value="玉林市犀浦镇牛羊市场" />
        <el-option label="贺州市龙州县牛羊市场" value="贺州市龙州县牛羊市场" />
      </el-select>
    </el-form-item>

    <el-form-item label="服务人员" prop="salesman">
      <el-select v-model="ruleForm.salesman" placeholder="服务人员">
        <el-option label="刘永刚" value="刘永刚" />
        <el-option label="孟盘龙" value="孟盘龙" />
        <el-option label="赵秋实" value="赵秋实" />
        <el-option label="牛骞若" value="牛骞若" />
        <el-option label="赵思彤" value="赵思彤" />
        <el-option label="于晋哲" value="于晋哲" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        创建
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  <el-dialog v-model="dialogVisible" title="Tips" width="500" :before-close="handleClose">
    <mapSupplier />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import purcure from '@/api/PurchaseMent/index'
import { purcoreQuery, buildingIdQuery } from '@/api/PurchaseMent/model'
import vendor from '@/api/VendorMangMent/index'
import { vendorQuery } from '@/api/VendorMangMent/model'
import { ElMessage, ElMessageBox } from 'element-plus'
import { defineComponent, onUnmounted } from 'vue';
import AMapLoader from "@amap/amap-jsapi-loader";
import mapSupplier from './city/Map.vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//参数
const ruleForm = reactive({
  "venDorCode": "",//供应商编号
  "vendorType": "",//供应商类型
  "responsiblePhone": "",//负责人电话
  "responsibleName": "",//负责人姓名
  "vendorName": "",//供应商名称
  "identityCard": "",//身份证
  "arearAdd": "",//地址
  "industryName": "",//所属行业
  "unifiedSocialCreditCode": "",//统一社会信用代码
  "mnemonics": "",//助记码
  "vendorAttributes": "",//供应商属性
  "businessId": null,//所属单位
  "useState": true,//使用状态（使用，停用）
  "unitsOfReference": "",//引用单位
  "vendorDesc": "",//备注
  "markets": "",//所属市场（服务人员）
  "salesman": "",//业务员
  "createBy": 0,//创建人
  "createTime": "2024-07-27",//创建时间
  "updateBy": 0,//修改人
  "updateTime": "2024-07-27",//修改时间
  "isDel": false//是否删除
})
//全国省市县
import data from 'province-city-china/dist/level.json'
//刷新数据
const emit = defineEmits(["addOK"]);
//#region 省市县级联
const value = ref([]);
const options = ref([]);
const handleChange = (value: any) => {

};
const prop = {
  checkStrictly: true,
  expandTrigger: "hover" as const,
};

const defaults = {
  props: {
    children: "children",
  },
};

onMounted(() => {
  options.value = data;
  options.value = options.value.map((item) => {
    return {
      value: item.code,
      label: item.name,
      children: item.children?.map((item2) => {
        return {
          value: item2.code,
          label: item2.name,
          children: item2.children?.map((item3) => {
            return {
              value: item3.code,
              label: item3.name,
            };
          }),
        };
      }),
    };
  });

  console.log(options.value);
});

//表单验证
const rules = reactive<FormRules<RuleForm>>({
  venDorCode: [
    { required: true, message: '供应商编号不能为空', trigger: 'blur' },
  ],
  vendorType: [
    { required: true, message: '供应商类型不能为空', trigger: 'blur' },
  ],
  responsiblePhone: [
    { required: true, message: "请输入负责人手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  responsibleName: [
    { required: true, message: '负责人姓名不能为空', trigger: 'blur' },
  ],
  identityCard: [
    { required: true, message: "请填写身份证", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  vendorName: [
    { required: true, message: '供应商类型不能为空', trigger: 'blur' },
  ],
  arearAdd: [
    { required: true, message: '地址不能为空', trigger: 'blur' },
  ],
  industryName: [
    { required: true, message: '所属行业不能为空', trigger: 'blur' },
  ],
  unifiedSocialCreditCode: [
    { required: true, message: '统一社会信用代码不能为空', trigger: 'blur' },
  ],
  mnemonics: [
    { required: true, message: '助记码不能为空', trigger: 'blur' },
  ],
  vendorAttributes: [
    { required: true, message: '供应商属性不能为空', trigger: 'blur' },
  ],
  businessId: [
    { required: true, message: '所属单位不能为空', trigger: 'blur' },
  ],
  useState: [
    { required: true, message: '使用状态', trigger: 'blur' },
  ],
  unitsOfReference: [
    { required: true, message: '引用单位不能为空', trigger: 'blur' },
  ],
  vendorDesc: [
    { required: true, message: '备注不能为空', trigger: 'blur' },
  ],
  markets: [
    { required: true, message: '所属市场不能为空', trigger: 'blur' },
  ],
  salesman: [
    { required: true, message: '业务员不能为空', trigger: 'blur' },
  ],
})
//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      vendor.addpur(ruleForm).then(res => {
        if (res.code > 0) {
          ElMessage.success('添加成功');

        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//地图
let map: any = null; // Define map variable with proper type
let placeSearch: any = null; // Define placeSearch variable

function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: "0e64b586350a7d7cc08c9d0be36e8923", // 密钥
  };	// Important!
  AMapLoader.load({
    key: "3901bbb7e4598de04e06cabcf21f2b47", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.AutoComplete',
      'AMap.PlaceSearch'
    ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        resizeEnable: true,
        viewMode: "3D", // 是否为3D地图模式
        zoom: 8, // 初始化地图级别
        center: [118, 30], // 初始化地图中心点位置
      });
      const autoOptions = {
        input: "searchInputId"
      };
      const auto = new AMap.AutoComplete(autoOptions);
      placeSearch = new AMap.PlaceSearch({
        map: map
      });
      auto.on("select", handleSelect);
    });
}

function handleSelect(e: any) {
  placeSearch.setCity(e.poi.adcode);
  placeSearch.search(e.poi.name, (status: string, result: any) => {
    if (status === 'complete' && result.info === 'OK') {
      // Assuming first result contains detailed address info
      const selectedLocation = result.poiList.pois[0];
      const addressInfo = `${selectedLocation.name}, ${selectedLocation.address}`;
      console.log("Selected location:", addressInfo);
      // Set state to display detailed address info
      selectedLocationInfo.value = addressInfo;
      ruleForm.arearAdd = selectedLocation.name

    }
  });
}

onMounted(() => {
  console.log("onmounted");
  initMap();
});

onUnmounted(() => {
  if (map) {
    map.destroy();
  }
});

const selectedLocationInfo = ref(''); // Reactive variable to hold detailed address info

const searchLocation = () => {
  dialogVisible.value = true
}
</script>
